﻿using System;
using System.Web.Http;
using System.Web.Http.Controllers;

using Flagwind.Plugins;

namespace Flagwind.Web.Plugins
{
	public class PluginHttpControllerDescriptor : HttpControllerDescriptor
	{
		#region 成员字段

		private PluginTreeNode _controllerNode;

		#endregion

		#region 公共属性

		public PluginTreeNode ControllerNode
		{
			get
			{
				return _controllerNode;
			}
		}

		#endregion

		#region 构造方法

		public PluginHttpControllerDescriptor(HttpConfiguration configuration, PluginTreeNode controllerNode)
		{
			if(configuration == null)
				throw new ArgumentNullException(nameof(configuration));

			if(controllerNode == null)
				throw new ArgumentNullException(nameof(controllerNode));

			_controllerNode = controllerNode;
			this.Configuration = configuration;
			this.ControllerName = controllerNode.Name;

			switch(controllerNode.NodeType)
			{
				case PluginTreeNodeType.Builtin:
					this.ControllerType = ((Builtin)controllerNode.Value).BuiltinType.Type;
					break;
				case PluginTreeNodeType.Custom:
					if(controllerNode.Value != null)
						this.ControllerType = controllerNode.Value.GetType();
					break;
			}
		}

		#endregion

		#region 重写方法

		public override IHttpController CreateController(System.Net.Http.HttpRequestMessage request)
		{
			return _controllerNode.UnwrapValue<IHttpController>(ObtainMode.Alway, request, null);
		}

		#endregion
	}
}
